<template>
  <div class="bind-container">
    <!-- 用户信息显示 -->
    <el-card v-if="user" class="user-info-card" shadow="never" style="margin-bottom: 20px;">
      <div slot="header" class="clearfix">
        <span style="font-weight: bold;">用户信息</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="info-item">
            <span class="info-label">用户名称：</span>
            <span class="info-value">{{ user.userName }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="info-label">用户昵称：</span>
            <span class="info-value">{{ user.nickName }}</span>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="info-item">
            <span class="info-label">手机号码：</span>
            <span class="info-value">{{ user.phonenumber }}</span>
          </div>
        </el-col>
      </el-row>
     
    </el-card>

    <!-- 简化的查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px" v-if="!userId">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 简化的操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增绑定</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="bindList" :height="300">
      <el-table-column label="微信昵称" align="center" prop="nickname" />
      <el-table-column label="微信OpenID" align="center" prop="openId" show-overflow-tooltip />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="绑定状态" align="center" prop="bindStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.bindStatus === 1 ? 'success' : 'danger'">
            {{ scope.row.bindStatus === 1 ? '已绑定' : '已解绑' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center" prop="lastLoginTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
       
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户微信绑定对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!-- 二维码显示区域 -->
      <div v-if="showQrCode" class="qr-code-container">
        <div class="qr-code-header">
          <h3>微信授权绑定</h3>
          <p>请使用微信扫描下方二维码进行授权绑定</p>
        </div>
        <div class="qr-code-content">
          <div class="qr-code">
            <div v-if="qrCodeLoading" class="qr-code-loading">
              <div class="loading-spinner"></div>
              <p>生成中...</p>
            </div>
            <img v-else-if="qrCodeImage" :src="qrCodeImage" alt="微信授权绑定二维码" />
            <div v-else class="qr-code-error" @click="refreshQrCode">
              <p>二维码生成失败</p>
              <p>点击重试</p>
            </div>
          </div>
          <div class="qr-code-info">
            <p><strong>用户信息：</strong></p>
            <p>用户名：{{ user ? user.userName : '' }}</p>
            <p>手机号：{{ user ? user.phonenumber : '' }}</p>
          </div>
        </div>
        <div class="qr-code-tips">
          <el-alert
            title="扫码说明"
            type="info"
            :closable="false"
            show-icon>
            <p>1. 请使用微信扫描上方二维码</p>
            <p>2. 在微信中完成授权操作</p>
            <p>3. 授权成功后会自动绑定到当前用户</p>
          </el-alert>
        </div>
      </div>
      
      <!-- 原有的表单编辑区域 -->
      <el-form v-else ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" :disabled="!!userId" />
        </el-form-item>
        <el-form-item label="微信OpenID" prop="openId">
          <el-input v-model="form.openId" placeholder="请输入微信OpenID" />
        </el-form-item>
        <el-form-item label="微信UnionID" prop="unionId">
          <el-input v-model="form.unionId" placeholder="请输入微信UnionID" />
        </el-form-item>
        <el-form-item label="微信昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入微信昵称" />
        </el-form-item>
        <el-form-item label="微信头像" prop="avatarUrl">
          <el-input v-model="form.avatarUrl" type="textarea" placeholder="请输入头像URL" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="绑定状态" prop="bindStatus">
          <el-radio-group v-model="form.bindStatus">
            <el-radio :label="1">已绑定</el-radio>
            <el-radio :label="0">已解绑</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button v-if="showQrCode" @click="refreshQrCode" type="primary" icon="el-icon-refresh">刷新二维码</el-button>
        <el-button v-else type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBind, getBind, delBind, addBind, updateBind } from "@/api/system/bind";
import QRCode from 'qrcode';

export default {
  name: "Bind",
  props: {
    userId: {
      type: [String, Number],
      default: null
    },
    user: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户微信绑定表格数据
      bindList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        openId: null,
        unionId: null,
        nickname: null,
        avatarUrl: null,
        phone: null,
        bindStatus: null,
        lastLoginTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        openId: [
          { required: true, message: "微信OpenID不能为空", trigger: "blur" }
        ],
        bindStatus: [
          { required: true, message: "绑定状态：0-解绑，1-已绑定不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      },
      // 是否显示二维码
      showQrCode: false,
      // 二维码加载状态
      qrCodeLoading: false,
      // 二维码图片
      qrCodeImage: null
    };
  },
  created() {
    this.getList();
  },
  watch: {
    userId: {
      handler(newVal) {
        if (newVal) {
          this.queryParams.userId = newVal;
          this.getList();
        }
      },
      immediate: true
    }
  },
  methods: {
    /** 查询用户微信绑定列表 */
    getList() {
      this.loading = true;
      listBind(this.queryParams).then(response => {
        this.bindList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: this.userId || null,
        openId: null,
        unionId: null,
        nickname: null,
        avatarUrl: null,
        phone: null,
        bindStatus: 1,
        lastLoginTime: null,
        createTime: null,
        updateTime: null
      };
      // 重置二维码相关状态
      this.showQrCode = false;
      this.qrCodeLoading = false;
      this.qrCodeImage = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if (this.userId) {
        this.form.userId = this.userId;
      }
      this.open = true;
      this.title = "添加用户微信绑定";
      this.showQrCode = true;
      
      // 生成二维码
      this.$nextTick(() => {
        this.generateQrCode();
      });
    },
    // 生成二维码
    generateQrCode() {
      this.qrCodeLoading = true;
      this.qrCodeImage = null;
      
      // 构建授权URL
      const baseUrl = 'https://hunantianwang.site/shouquan';
      const params = new URLSearchParams({
        userId: this.user ? this.user.userId : this.userId,
        userName: this.user ? this.user.userName : '',
        phone: this.user ? this.user.phonenumber : ''
      });
      const authUrl = `${baseUrl}?${params.toString()}`;
      
      // 使用本地qrcode库生成二维码
      QRCode.toDataURL(authUrl, {
        width: 200,
        margin: 2,
        color: {
          dark: '#000000',
          light: '#FFFFFF'
        }
      }).then(url => {
        this.qrCodeImage = url;
        this.qrCodeLoading = false;
      }).catch(err => {
        console.error('二维码生成失败:', err);
        this.qrCodeLoading = false;
        this.qrCodeImage = null;
        this.$message.error('二维码生成失败，请点击重试');
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBind(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户微信绑定";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBind(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBind(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户微信绑定编号为"' + ids + '"的数据项？').then(function() {
        return delBind(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/bind/export', {
        ...this.queryParams
      }, `bind_${new Date().getTime()}.xlsx`)
    },
    // 刷新二维码
    refreshQrCode() {
      this.generateQrCode();
    }
  }
};
</script>

<style scoped>
.user-info-card {
  border: 1px solid #e4e7ed;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-value {
  color: #303133;
  font-weight: 400;
}

.bind-container {
  padding: 0;
}

.qr-code-container {
  padding: 20px;
}

.qr-code-header {
  text-align: center;
  margin-bottom: 20px;
}

.qr-code-content {
  display: flex;
  justify-content: center;
  align-items: center;
}

.qr-code {
  width: 200px;
  height: 200px;
  margin-right: 20px;
  border: 1px solid #eef1f8;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.qr-code img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.qr-code canvas {
  width: 100%;
  height: 100%;
}

.qr-code-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(248, 250, 253, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.qr-code-loading .loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #4361ee;
  border-top: 3px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.qr-code-loading p {
  margin-top: 10px;
  font-size: 12px;
  color: #78839c;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.qr-code-info {
  text-align: left;
}

.qr-code-tips {
  margin-top: 20px;
  text-align: center;
}

.qr-code-error {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(248, 250, 253, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  cursor: pointer;
}

.qr-code-error p {
  margin-top: 10px;
  font-size: 12px;
  color: #78839c;
}
</style>
